//app.js
App({
  globalData: {
    userInfo: null,
    isLoggedIn: false,
    // 全局配置
    config: {
      baseUrl: '', // 后端API地址
      pageSize: 10
    }
  },

  onLaunch: function() {
    // 初始化云开发环境
    // 这里可以根据需要初始化云开发环境

    // 检查登录状态
    this.checkLoginStatus();

    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    this.globalData.systemInfo = systemInfo;
  },

  checkLoginStatus: function() {
    // 从本地存储获取登录状态
    const userInfo = wx.getStorageSync('userInfo');
    const isLoggedIn = wx.getStorageSync('isLoggedIn');
    
    if (userInfo && isLoggedIn) {
      this.globalData.userInfo = userInfo;
      this.globalData.isLoggedIn = true;
    }
  },

  login: function(userInfo) {
    // 保存登录状态
    this.globalData.userInfo = userInfo;
    this.globalData.isLoggedIn = true;
    
    // 持久化到本地存储
    wx.setStorageSync('userInfo', userInfo);
    wx.setStorageSync('isLoggedIn', true);
  },

  logout: function() {
    // 清除登录状态
    this.globalData.userInfo = null;
    this.globalData.isLoggedIn = false;
    
    // 清除本地存储
    wx.removeStorageSync('userInfo');
    wx.removeStorageSync('isLoggedIn');
    
    // 跳转到登录页面
    wx.redirectTo({
      url: '/pages/login/login'
    });
  },

  // 显示提示信息
  showToast: function(title, icon = 'none', duration = 2000) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration
    });
  },

  // 显示加载提示
  showLoading: function(title = '加载中') {
    wx.showLoading({
      title: title
    });
  },

  // 隐藏加载提示
  hideLoading: function() {
    wx.hideLoading();
  },

  // 封装网络请求
  request: function(options) {
    const defaultOptions = {
      url: '',
      method: 'GET',
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success: () => {},
      fail: () => {},
      complete: () => {}
    };

    const finalOptions = Object.assign({}, defaultOptions, options);
    
    // 如果配置了baseUrl，则添加到url前面
    if (this.globalData.config.baseUrl && !finalOptions.url.startsWith('http')) {
      finalOptions.url = this.globalData.config.baseUrl + finalOptions.url;
    }

    // 添加token到请求头（如果已登录）
    if (this.globalData.isLoggedIn && this.globalData.userInfo.token) {
      finalOptions.header['Authorization'] = `Bearer ${this.globalData.userInfo.token}`;
    }

    wx.request(finalOptions);
  }
})